package com.ruoyi.report_ljlm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_gc.domain.GcqfqdklqddhsclzdlzysljlbBsDetail;
import com.ruoyi.report_ljlm.domain.ReportLjlmPzdsmzcBaDetail;
import com.ruoyi.report_ljlm.domain.ReportLjlmPzdsmzcbgBaDetail;
import com.ruoyi.report_ljlm.domain.vo.ReportLjlmPzdsmzcbgBaDetailVo;
import com.ruoyi.report_ljlm.mapper.ReportLjlmPzdsmzcbgBaDetailMapper;
import com.ruoyi.report_tg.domain.TgsybgBaDetail;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.report_ys.domain.bo.ReportYsDzkyqdsybgBsInfoBo;
import com.ruoyi.report_ys.domain.vo.ReportYsDzkyqdsybgBaDetailVo;
import com.ruoyi.sycs.service.IBiQualificationService;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_ljlm.domain.bo.ReportLjlmPzdsmzcbgBsInfoBo;
import com.ruoyi.report_ljlm.domain.vo.ReportLjlmPzdsmzcbgBsInfoVo;
import com.ruoyi.report_ljlm.domain.ReportLjlmPzdsmzcbgBsInfo;
import com.ruoyi.report_ljlm.mapper.ReportLjlmPzdsmzcbgBsInfoMapper;
import com.ruoyi.report_ljlm.service.IReportLjlmPzdsmzcbgBsInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 路基路面平整度试验检测报告三米直尺法Service业务层处理
 *
 * @author zyb
 * @date 2024-10-29
 */
@RequiredArgsConstructor
@Service
@Transactional
public class ReportLjlmPzdsmzcbgBsInfoServiceImpl implements IReportLjlmPzdsmzcbgBsInfoService {

    private final ReportLjlmPzdsmzcbgBsInfoMapper baseMapper;
    private final ReportLjlmPzdsmzcbgBaDetailMapper detailMapper;
    private final ISysDictDataService dictService;
    private final IBiQualificationService biQualificationService;

    /**
     * 查询路基路面平整度试验检测报告三米直尺法
     */
    @Override
    @FIllBasicInfo
    public ReportLjlmPzdsmzcbgBsInfoVo queryById(Long excelId){
        ReportLjlmPzdsmzcbgBsInfoVo reportLjlmPzdsmzcbgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<ReportLjlmPzdsmzcbgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<ReportLjlmPzdsmzcbgBaDetail>()
            .eq(ReportLjlmPzdsmzcbgBaDetail::getExcelId, excelId));
        //格式化
        compute(reportLjlmPzdsmzcbgBsInfoVo,baDetailVos);
        reportLjlmPzdsmzcbgBsInfoVo.setBaDetailVos(baDetailVos);
        if (StringUtils.isNotEmpty(reportLjlmPzdsmzcbgBsInfoVo.getJiancjl()) && "检测结论：".equals(reportLjlmPzdsmzcbgBsInfoVo.getJiancjl())){
            return reportLjlmPzdsmzcbgBsInfoVo;
        }
        return jcjl(reportLjlmPzdsmzcbgBsInfoVo);
    }

    private ReportLjlmPzdsmzcbgBsInfoVo jcjl(ReportLjlmPzdsmzcbgBsInfoVo reportLjlmPzdsmzcbgBsInfoVo) {
        List<ReportLjlmPzdsmzcbgBaDetailVo> baDetailVos = reportLjlmPzdsmzcbgBsInfoVo.getBaDetailVos();
        if (CollectionUtils.isNotEmpty(baDetailVos)){
            boolean flag = baDetailVos.stream().anyMatch(dv -> "不符合".equals(dv.getJiegpd()));
            if (flag){
                return reportLjlmPzdsmzcbgBsInfoVo;
            }
        }
        String result = "检测结论：经检测，所检项目符合" +
            reportLjlmPzdsmzcbgBsInfoVo.getPandyj() + "规范要求。";
        reportLjlmPzdsmzcbgBsInfoVo.setJiancjl(result);
        return reportLjlmPzdsmzcbgBsInfoVo;
    }

    /**
     * 查询路基路面平整度试验检测报告三米直尺法列表
     */
    @Override
    public TableDataInfo<ReportLjlmPzdsmzcbgBsInfoVo> queryPageList(ReportLjlmPzdsmzcbgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ReportLjlmPzdsmzcbgBsInfo> lqw = buildQueryWrapper(bo);
        Page<ReportLjlmPzdsmzcbgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询路基路面平整度试验检测报告三米直尺法列表
     */
    @Override
    public List<ReportLjlmPzdsmzcbgBsInfoVo> queryList(ReportLjlmPzdsmzcbgBsInfoBo bo) {
        LambdaQueryWrapper<ReportLjlmPzdsmzcbgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ReportLjlmPzdsmzcbgBsInfo> buildQueryWrapper(ReportLjlmPzdsmzcbgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ReportLjlmPzdsmzcbgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, ReportLjlmPzdsmzcbgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, ReportLjlmPzdsmzcbgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), ReportLjlmPzdsmzcbgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), ReportLjlmPzdsmzcbgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), ReportLjlmPzdsmzcbgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), ReportLjlmPzdsmzcbgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), ReportLjlmPzdsmzcbgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), ReportLjlmPzdsmzcbgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), ReportLjlmPzdsmzcbgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsj()), ReportLjlmPzdsmzcbgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), ReportLjlmPzdsmzcbgBsInfo::getJiancrq, bo.getJiancrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), ReportLjlmPzdsmzcbgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), ReportLjlmPzdsmzcbgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), ReportLjlmPzdsmzcbgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), ReportLjlmPzdsmzcbgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), ReportLjlmPzdsmzcbgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getQuywz()), ReportLjlmPzdsmzcbgBsInfo::getQuywz, bo.getQuywz());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), ReportLjlmPzdsmzcbgBsInfo::getWeitrwbh, bo.getWeitrwbh());
        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), ReportLjlmPzdsmzcbgBsInfo::getTuycd, bo.getTuycd());
        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), ReportLjlmPzdsmzcbgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), ReportLjlmPzdsmzcbgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), ReportLjlmPzdsmzcbgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), ReportLjlmPzdsmzcbgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), ReportLjlmPzdsmzcbgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), ReportLjlmPzdsmzcbgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), ReportLjlmPzdsmzcbgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), ReportLjlmPzdsmzcbgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), ReportLjlmPzdsmzcbgBsInfo::getPandyjIds, bo.getPandyjIds());
        lqw.eq(bo.getExcelResult() != null, ReportLjlmPzdsmzcbgBsInfo::getExcelResult, bo.getExcelResult());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitbh()), ReportLjlmPzdsmzcbgBsInfo::getWeitbh, bo.getWeitbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJianclb()), ReportLjlmPzdsmzcbgBsInfo::getJianclb, bo.getJianclb());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancld()), ReportLjlmPzdsmzcbgBsInfo::getJiancld, bo.getJiancld());
        lqw.eq(StringUtils.isNotBlank(bo.getJiegcc()), ReportLjlmPzdsmzcbgBsInfo::getJiegcc, bo.getJiegcc());
        lqw.eq(bo.getZongcs() != null, ReportLjlmPzdsmzcbgBsInfo::getZongcs, bo.getZongcs());
        lqw.eq(bo.getHegcs() != null, ReportLjlmPzdsmzcbgBsInfo::getHegcs, bo.getHegcs());
        lqw.eq(bo.getHegl() != null, ReportLjlmPzdsmzcbgBsInfo::getHegl, bo.getHegl());
        return lqw;
    }

    /**
     * 新增路基路面平整度试验检测报告三米直尺法
     */
    @Override
    @DSTransactional
    public Boolean insertByBo(ReportLjlmPzdsmzcbgBsInfoBo bo) {
        ReportLjlmPzdsmzcbgBsInfo add = BeanUtil.toBean(bo, ReportLjlmPzdsmzcbgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            ArrayList<ReportLjlmPzdsmzcbgBaDetail> details = new ArrayList<>(10);
            for (int i = 1; i <= 10; i++) {
                details.add(new ReportLjlmPzdsmzcbgBaDetail(bo.getExcelId(), Long.parseLong(String.valueOf(i))));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改路基路面平整度试验检测报告三米直尺法
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(ReportLjlmPzdsmzcbgBsInfoBo bo) {
        //是否合格的填充
        fillExcelResult(bo);
        ReportLjlmPzdsmzcbgBsInfo update = BeanUtil.toBean(bo, ReportLjlmPzdsmzcbgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag){
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos(), ReportLjlmPzdsmzcbgBaDetail.class));
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ReportLjlmPzdsmzcbgBsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    private void fillExcelResult(ReportLjlmPzdsmzcbgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            bo.setExcelResult(2);
        }
        bo.setExcelResult(0);
    }
    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }
    /**
     * 批量删除路基路面平整度试验检测报告三米直尺法
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public List<ReportLjlmPzdsmzcbgBaDetailVo> compute(ReportLjlmPzdsmzcbgBsInfoVo reportLjlmPzdsmzcbgBsInfoVo,List<ReportLjlmPzdsmzcbgBaDetailVo> voList) {
        voList.forEach(v -> {
//            if (ObjUtil.isNull(v.getQualId())) {
//                throw new ServiceException("qualId不能为空");
//            }
//            // 1. 根据不同符号 格式化技术指标 && 结果判定
//            if (StrUtil.isEmpty(v.getSymbolValue())) {
//                v.setJiszb("-");
//                if (ObjUtil.isNotNull(v.getJiancjg())) {
//                    v.setJiegpd("实测值");
//                } else {
//                    v.setJiegpd("-");
//                }
//                return;
//            }
            if (StringUtils.isNotEmpty(v.getSymbolValue())){
                switch (v.getSymbolValue()) {
                    case "01":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "01") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "02":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "02") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "03":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "03") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) == 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "04":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "04") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "05":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "05") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) >= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "06":
                        if (ObjUtil.isNotNull(v.getNum1())) {
                            v.setJiszb(dictService.selectDictLabel("symbol",
                                "06") + BigDecimalUtil.stpTrailZero(v.getNum1()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().abs().compareTo(v.getNum1().abs()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "07":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb("≥" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",≤" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) >= 0 && v.getJiancjg().compareTo(v.getNum2()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "08":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb(">" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",≤" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0 && v.getJiancjg().compareTo(v.getNum2()) <= 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "09":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb("≥" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",<" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) >= 0 && v.getJiancjg().compareTo(v.getNum2()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                    case "10":
                        if (ObjUtil.isNotNull(v.getNum1()) && ObjUtil.isNotNull(v.getNum2())) {
                            v.setJiszb(">" + BigDecimalUtil.stpTrailZero(v.getNum1()) + ",<" + BigDecimalUtil.stpTrailZero(v.getNum2()));
                            if (ObjUtil.isNotNull(v.getJiancjg())) {
                                if (v.getJiancjg().compareTo(v.getNum1()) > 0 && v.getJiancjg().compareTo(v.getNum2()) < 0) {
                                    v.setJiegpd("符合");
                                } else {
                                    v.setJiegpd("不符合");
                                }
                            } else {
                                v.setJiegpd("-");
                            }
                        } else {
                            throw new ServiceException(biQualificationService.queryById(v.getQualId()).getQualName() + "技术指标不完整，无法计算");
                        }
                        break;
                }
            }
        });
        List<ReportLjlmPzdsmzcbgBaDetailVo> list = voList.stream().filter(v -> Objects.nonNull(v.getJiszb()) && v.getJiegpd().equals("合格")).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list)){
            reportLjlmPzdsmzcbgBsInfoVo.setHegl((long) (list.size() / voList.size()) * 100);
        }
        return voList;
    }
}
